#pragma once
#include "log.hpp"
#include "protocol.hpp"
#include <cstdlib>
#include <cstring>
#include <string>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <sys/wait.h>
namespace Server
{
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR
    };
    static const uint16_t gport = 8080;
    static const int gbacklog = 5;
    typedef std::function<bool(const Request &, Response &r)> func_t;
    void handlerEntery(int sock, func_t func)
    {
        std::string inbuffer;
        while (true)
        {
            std::string package, text;
            if (!recvPackage(sock, inbuffer, &package))
            {
                return;
            }
            std::cout << "带报头的请求: \n"
                      << package << std::endl;
            if (!deLength(package, &text))
            {
                return;
            }
            std::cout << "去掉报头的正文 : \n"
                      << text << std::endl;
            Request req;
            if (!req.deserialize(text))
                return;
            Response resp;
            func(req, resp);
            std::string resp_text;
            resp.serialize(&resp_text);
            std::cout << "计算完成, 序列化响应: " << resp_text << std::endl;
            std::string send_string = enLength(resp_text);
            std::cout << "构建完成完整的响应: \n"
                      << send_string << std::endl;
            send(sock, send_string.c_str(), send_string.size(), 0);
        }
    }
    class CalServer
    {
    public:
        CalServer(const uint16_t &port = gport)
            : _port(port), _listensock(-1)
        {
        }
        void initServer()
        {
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                logMessage(FATAL, "create socket error");
                exit(SOCKET_ERR);
            }
            logMessage(NORMAL, "create socket success : %d", _listensock);
            int opt = 1;
            setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = htonl(INADDR_ANY);
            local.sin_port = htons(_port);
            if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                logMessage(FATAL, "bind socket error");
                exit(BIND_ERR);
            }
            logMessage(NORMAL, "bind socket success");
            if (listen(_listensock, gbacklog) < 0)
            {
                logMessage(FATAL, "listen socket error");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL, "listen socket success");
        }
        void start(func_t func)
        {
            for (;;)
            {
                struct sockaddr_in client;
                memset(&client, 0, sizeof(client));
                socklen_t len = sizeof(client);
                int sock = accept(_listensock, (struct sockaddr *)&client, &len);
                if (sock < 0)
                {
                    logMessage(ERROR, "accept error, next");
                    continue;
                }
                logMessage(NORMAL, "accept a new link success, get new sock : %d", sock);
                pid_t id = fork();
                if (id == 0)
                {
                    close(_listensock);
                    if (fork() > 0)
                        exit(0);
                    handlerEntery(sock, func);
                    close(sock);
                    exit(0);
                }
                close(sock);
                int n = waitpid(id, nullptr, 0);
                if (n > 0)
                {
                    logMessage(NORMAL, "wait child success");
                }
            }
        }
        ~CalServer()
        {
        }

    private:
        int _listensock;
        uint16_t _port;
    };
}